package com.zk.zkserver;

import org.apache.zookeeper.*;

import java.io.IOException;

/**
 * 服务器端向Zookeeper注册代码
 */
public class DistributeServer {

    // zookeeper连接地址,中间不要有空格
    private String connectString = "192.168.189.150:2181,192.168.189.151:2181,192.168.189.152:2181";

    // 连接超时时间2000毫秒
    private int sessionTimeOut = 2000;

    private ZooKeeper zkClient;

    private String parentNode = "/servers";

    public static void main(String[] args) throws Exception {
        // 1 获取 zk 连接
        DistributeServer server = new DistributeServer();
        server.getConnection();
        // 2 利用 zk 连接注册服务器信息
        //args[0]获取main方法的参数
        server.registServer(args[0]);
        // 3 启动业务功能
        server.business(args[0]);
    }

    //创建到zk的客户端连接
    public void getConnection() {
        Watcher watcher;
        try {
            zkClient = new ZooKeeper(connectString, sessionTimeOut, new Watcher() {
                @Override
                public void process(WatchedEvent watchedEvent) {

                }
            });
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    //注册服务器
    public void registServer(String hostname) throws KeeperException, InterruptedException {
        String create = zkClient.create(parentNode + "/server", hostname.getBytes(), ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.EPHEMERAL_SEQUENTIAL);
        System.out.println(hostname + "is working ..." + create);
    }

//    Exception in thread "main" org.apache.zookeeper.KeeperException$NoNodeException: KeeperErrorCode = NoNode for /servers/server
//    去zookeeper集群创建/servers/server

    // 业务功能
    public void business(String hostname) throws Exception {
        System.out.println(hostname + " is working ...");
        Thread.sleep(Long.MAX_VALUE);
    }


}
